package com.libs.sys.service.impl;

import com.libs.sys.model.Userseat;
import com.libs.sys.service.LibService;
import com.libs.utils.*;
import lombok.extern.slf4j.Slf4j;
import org.apache.commons.io.FileUtils;
import org.apache.commons.lang3.StringUtils;
import org.apache.http.client.methods.CloseableHttpResponse;
import org.apache.http.impl.client.CloseableHttpClient;
import org.apache.http.message.BasicNameValuePair;
import org.apache.http.util.EntityUtils;
import org.jsoup.Jsoup;
import org.springframework.stereotype.Service;

import java.io.File;
import java.net.URI;
import java.net.URLDecoder;
import java.util.ArrayList;
import java.util.Calendar;
import java.util.List;
import java.util.Random;

/**
 * @author yzr07
 */

@Service
@Slf4j
public class LibServiceImpl implements LibService {
    String MM, dd, mm, hh = "";
    int year = 0;
    private final TestImgV1 testImgV1 = new TestImgV1();

    public LibServiceImpl() {
        Calendar calendar = Calendar.getInstance();
        int year = calendar.get(Calendar.YEAR);
        int month = calendar.get(Calendar.MONTH) + 1;
        int day = calendar.get(Calendar.DAY_OF_MONTH);
        int hour = calendar.get(Calendar.HOUR_OF_DAY);
        int min = calendar.get(Calendar.MINUTE);
        if (month < 10) {
            MM = "0" + month;
        } else {
            MM = "" + month;
        }
        if (day < 10) {
            dd = "0" + day;
        } else {
            dd = "" + day;
        }
        if (hour < 10) {
            hh = "0" + hour;
        } else {
            hh = "" + hour;
        }
        if (min < 10) {
            mm = "0" + min;
        } else {
            mm = "" + min;
        }
        this.year = year;
    }

//    @Override
//    public String login(Userseat userseat, CloseableHttpClient httpClient) throws Exception {
//        try {
//            String url = "https://lib-seat.chu.edu.cn/ClientWeb/pro/ajax/login.aspx?act=login&id=" + userseat.getUid() + "&pwd=" + userseat.getPwd() + "&role=512&aliuserid=&schoolcode=&wxuserid=&_nocache=1624506443276";
//            CloseableHttpResponse getRes = HttpClientConn.getGetRes(url, true, httpClient);
//            String body = EntityUtils.toString(getRes.getEntity());
//            return body.substring(StringUtils.ordinalIndexOf(body, "\"", 23) + 1,
//                    StringUtils.ordinalIndexOf(body, "\"", 24));
//        } catch (Exception e) {
////            StringIndexOutOfBoundsException |
////                    SocketTimeoutException |
////                    ConnectException e
//            log.info("{}登录超时！", userseat.getUid());
//        }
//        return "-1";
//    }

    @Override
    public String login(Userseat userseat, CloseableHttpClient httpClient) throws Exception {
        try {
//            String number = testImgV1.getNumber("https://lib-seat.chu.edu.cn/ClientWeb/pro/page/image.aspx?", httpClient);
            String number= TestImgV1.getNumber(httpClient,true);
//            String number=BaiduOCR.getCode(userseat,httpClient,true);
            String url = "https://lib-seat.chu.edu.cn/ClientWeb/pro/ajax/login.aspx?act=login&id=" + userseat.getUid() + "&pwd=" + userseat.getPwd() + "&number=" + number + "&role=512&aliuserid=&schoolcode=&wxuserid=&_nocache=1624506443276";
            CloseableHttpResponse getRes = HttpClientConn.getGetRes(url, false, httpClient);
            String body = EntityUtils.toString(getRes.getEntity());
            return body.substring(StringUtils.ordinalIndexOf(body, "\"", 23) + 1,
                    StringUtils.ordinalIndexOf(body, "\"", 24));
        } catch (Exception e) {
//            StringIndexOutOfBoundsException |
//                    SocketTimeoutException |
//                    ConnectException e
            log.info("{}登录超时！", userseat.getUid());
        }
        return "-1";
    }

    @Override
    public char setSeat(Userseat userseat, CloseableHttpClient httpClient) throws Exception {
        char res = '0';
        try {
//            String vnumber=testImgV1.getNumber("https://lib-seat.chu.edu.cn/ClientWeb/pro/page/image.aspx?"+new Random().nextDouble(), httpClient);
            String vnumber=TestImgV1.getNumber(httpClient,false);
//            String vnumber=BaiduOCR.getCode(userseat,httpClient,false);
            String url = "https://lib-seat.chu.edu.cn/ClientWeb/pro/ajax/reserve.aspx?dialogid=&dev_id=" + userseat.getSeatid() + "&lab_id=100455370&kind_id=&room_id=100455376&type=dev&prop=&test_id=&term=&number=&classkind=&test_name=&start=" + year + "-" + MM + "-" + dd + "+05%3A30&end=" + year + "-" + MM + "-" + dd + "+21%3A00&start_time=05%3A30&end_time=2100&up_file=&memo=&Vnumber="+vnumber+"&act=set_resv&_=187265345675";
//            String url = "https://lib-seat.chu.edu.cn/ClientWeb/pro/ajax/reserve.aspx?dialogid=&dev_id=" + userseat.getSeatid() + "&lab_id=100455374&kind_id=&room_id=100456481&type=dev&prop=&test_id=&term=&number=&classkind=&test_name=&start=" + year + "-" + MM + "-" + dd + "+05%3A30&end=" + year + "-" + MM + "-" + dd + "+21%3A00&start_time=05%3A30&end_time=2100&up_file=&memo=&act=set_resv&_=187265345675";
            CloseableHttpResponse getRes = HttpClientConn.getGetRes(url, true, httpClient);
            String body = EntityUtils.toString(getRes.getEntity());
//            System.out.println(body);
            String resUrl = URLDecoder.decode(URLDecoder.decode(body, "utf-8"), "utf-8");
            if(resUrl.contains("当日不能再预约")){
                return '1';
            }
            return body.charAt(7);
        } catch (Exception e) {
            log.info("{}抢座连接超时！", userseat.getUid());
            return res;
        }
    }

    @Override
    public char setSeat2(Userseat userseat, CloseableHttpClient httpClient, int rid) throws Exception {
        char res = '0';
        String roomid = "";
        if(rid==2){
            roomid="100455382";
        }else if (rid==3){
            roomid="100455384";
        }else if (rid==4){
            roomid="100456481";
        }else{
            return res;
        }
        try {
//            String vnumber=testImgV1.getNumber("https://lib-seat.chu.edu.cn/ClientWeb/pro/page/image.aspx?"+new Random().nextDouble(), httpClient);
            String vnumber=BaiduOCR.getCode(userseat,httpClient,false);
            String url = "https://lib-seat.chu.edu.cn/ClientWeb/pro/ajax/reserve.aspx?dialogid=&dev_id=" + userseat.getSeatid() + "&lab_id=100455374&kind_id=&room_id="+roomid+"&type=dev&prop=&test_id=&term=&number=&classkind=&test_name=&start=" + year + "-" + MM + "-" + dd + "+05%3A30&end=" + year + "-" + MM + "-" + dd + "+21%3A00&start_time=05%3A30&end_time=2100&up_file=&memo=&Vnumber="+vnumber+"&act=set_resv&_=187265345675";
//            String url = "https://lib-seat.chu.edu.cn/ClientWeb/pro/ajax/reserve.aspx?dialogid=&dev_id=" + userseat.getSeatid() + "&lab_id=100455374&kind_id=&room_id=100456481&type=dev&prop=&test_id=&term=&number=&classkind=&test_name=&start=" + year + "-" + MM + "-" + dd + "+05%3A30&end=" + year + "-" + MM + "-" + dd + "+21%3A00&start_time=05%3A30&end_time=2100&up_file=&memo=&act=set_resv&_=187265345675";
            CloseableHttpResponse getRes = HttpClientConn.getGetRes(url, true, httpClient);
            String body = EntityUtils.toString(getRes.getEntity());
//            System.out.println(body);
            return body.charAt(7);
        } catch (Exception e) {
            log.info("{}抢座连接超时！", userseat.getUid());
            return res;
        }
    }

    /**
     * 生成随机码 msn
     *
     * @return
     */
    String gteRand() {
        Random r = new Random();
        String[] rands = {"0", "1", "2", "3", "4", "5", "6", "7", "8", "9", "a", "b", "c", "d", "e", "f"};
        String rand = "";
        for (int i = 0; i < 32; i++) {
            rand += rands[r.nextInt(16)];
        }
        return rand;
    }

    @Override
    public boolean signSeat(Userseat userseat, CloseableHttpClient httpClient) throws Exception {
        try {
            String msn = gteRand();
            String seatUrl = "http://lib-seat.chu.edu.cn/Pages/WxSeatSign.aspx?sta=1&sysid=1FD&lab=100455370&dev=" + userseat.getSeatid() + "&msn=" + msn + "&ls=true";
//            String seatUrl = "http://lib-seat.chu.edu.cn/Pages/WxSeatSign.aspx?sta=1&sysid=1FD&lab=100455374&dev=" + userseat.getSeatid() + "&msn=" + msn + "&ls=true";
            HttpClientConn.getGetRes(seatUrl, true, httpClient);
            String url = "https://lib-seat.chu.edu.cn/Pages/WxSeatSign.aspx";
            ArrayList<BasicNameValuePair> parameters = new ArrayList<>();
            parameters.add(new BasicNameValuePair("DoLogon", "true"));
            parameters.add(new BasicNameValuePair("sysidform", "1FD"));
            parameters.add(new BasicNameValuePair("aluseridform", msn));
            parameters.add(new BasicNameValuePair("wxuseridform", ""));
            parameters.add(new BasicNameValuePair("szLogonName", userseat.getUid()));
            parameters.add(new BasicNameValuePair("szPassword", userseat.getPwd()));
            CloseableHttpResponse postRes = HttpClientConn.getPostRes(url, parameters, false, httpClient);
            String body = EntityUtils.toString(postRes.getEntity());
            String attrUrl = Jsoup.parse(body).body().getElementsByTag("a").attr("href");
            //解码url地址
            String decodeUrl = URLDecoder.decode(new URI(attrUrl).getPath(), "utf-8");
            String resUrl = "";
            if (decodeUrl.contains("登录成功")) {
                String signSeatUrl = "https://lib-seat.chu.edu.cn/Pages/WxSeatSign.aspx?Userin=true";
                CloseableHttpResponse getRes = HttpClientConn.getGetRes(signSeatUrl, true, httpClient);
                String body1 = EntityUtils.toString(getRes.getEntity());
                resUrl = URLDecoder.decode(URLDecoder.decode(body1, "utf-8"), "utf-8");
            }
            return decodeUrl.contains("当前使用中") || resUrl.contains("签到成功");
        } catch (Exception e) {
            log.info("{}签到连接超时！", userseat.getUid());
        }
        return false;
    }

    @Override
    public void listExe(List<Userseat> userseatList) {
        List<MyThread> myThreads = new ArrayList<>();
        List<Thread> threads = new ArrayList<>();
        for (Userseat u
                : userseatList) {
            myThreads.add(new MyThread(u));
        }
        for (MyThread mt :
                myThreads) {
            threads.add(new Thread(mt));
        }
        for (Thread t :
                threads) {
            t.start();
        }
    }

    @Override
    public void listSign(List<Userseat> userseatList) {
        List<SignThread> signThreads = new ArrayList<>();
        List<Thread> threads = new ArrayList<>();
        for (Userseat u
                : userseatList) {
            signThreads.add(new SignThread(u));
        }
        for (SignThread st :
                signThreads) {
            threads.add(new Thread(st));
        }
        for (Thread t :
                threads) {
            t.start();
        }
    }

    public static void main(String[] args) throws Exception {
//        Userseat userseat = new Userseat("18037109", "131819", "100455732");
        Userseat userseat = new Userseat("18009053", "201554", "100456007");
//        Userseat userseat = UserSeatUtils.getUserSeatList().get(0);

        LibServiceImpl libService = new LibServiceImpl();
        CloseableHttpClient httpClient = HttpClientConn.getHttpClient();
        libService.login(userseat, httpClient);
        libService.setSeat(userseat, httpClient);
//        libService.signSeat(userseat, httpClient);

//        type=0&title=操作失败&msg=请使用本人预约的设备[第一自习室:088]&msg2=&ResvMsg=&status=0
//        type=4&title=当前使用中&msg=使用中,剩余时间【558分钟】[20:59]&msg2=&ResvMsg=设备预约信息:[5:32-21:00],&status=0
    }

    @Override
    public String getNumber(CloseableHttpClient httpClient) throws Exception {
        try {
            String url = "https://lib-seat.chu.edu.cn/ClientWeb/pro/page/image.aspx";
            CloseableHttpResponse getRes = HttpClientConn.getGetRes(url, true, httpClient);
            String body = EntityUtils.toString(getRes.getEntity());
            FileUtils.copyToFile(getRes.getEntity().getContent(), new File("G:\\project\\libs\\src\\main\\resources\\img\\1.jpeg"));
            return body;
        } catch (Exception e) {
            return "";
        }
    }

}
